import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button,  Dropdown, Menu,Descriptions,Divider,Row,Col,Card,Avatar,List,Skeleton,Statistic } from 'antd';
import Link from 'umi/link';
import { formatMessage } from 'umi-plugin-react/locale';
import React, { useState, useRef, useEffect} from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import DataForm from './components/DataForm';
import { TableListItem } from './data.d';
import { queryRule, updateRule, addRule, removeRule } from './service';
// import styles from './index.less';
import styles from './style.less';
import Radar from './components/Radar';

import {
    G2,
    Chart,
    Geom,
    Axis,
    Tooltip,
    Coord,
    Label,
    Legend,
    View,
    Guide,
    Shape,
    Facet,
    Util,
  } from 'bizcharts';
  import DataSet from '@antv/data-set';

import * as RequestHelper from '@/helpers/RequestHelper';
import PreviewForm from '@/components/PreviewForm';
import { FormValueType } from '@/pages/crm/depart/components/UpdateForm';
import * as TsxHelper from '@/helpers/TsxHelper';
import moment from 'moment';
interface TableListProps extends FormComponentProps {}


const TableList: React.FC<TableListProps> = () => {
    // 初始化变量区
    // 维护API状态数据
    const [apiState, setApiState] = useState<any>({common:{}});
    // 是否更新 关键变量
    const [isUpdate, setIsUpdate] = useState<boolean>(false);
    // 表单可见 关键变量
    const [dataModalVisible, handleDataModalVisible] = useState<boolean>(false);
    // 图片预览
    const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
    const [previewImg, setPreviewImg] = useState('');
    // 表单数据
    const [dataFormValues, setDataFormValues] = useState({});
    // 选中的记录
    const [rowKeys, setRowKeys] = useState<string[]|number[]>([]);
    const [detail,setDetail] = useState<any>({});
    const [currentUser, setCurrentUser] = useState<any>({});

    const actionRef = useRef<ActionType>();

    useEffect(()=>{
        queryRule().then(res=>{
            if(res.code == 0){
                setDetail(res.data)
            }
        }) 
    },[])

    // 请求接口数据, 设置组件状态
    const getTableData = (params:any) => {
        return queryRule(params).then((res:any) => {
            setApiState(res.data)
            return res.data.listData
        })
    }

    // 表单提交
    const handleSubmitDataForm = (value:any) => {
        return new Promise((resolve, reject) => {
            let s = isUpdate ? handleUpdate(value) : handleAdd(value);
            resolve(s);
        }).then( status => {
            console.log("handleSubmitDataForm status is ", status)
            if(status){
                handleDataModalVisible(false)
                setIsUpdate(false)
                setDataFormValues({})
                if (actionRef.current) {
                    actionRef.current.reload();
                }
            }
            // 返回执行结果:boolean, 子组件接收此值来重置数据
            return status;
        })
    }


    const gridStyle = {
      width: '33.33%',
    //   textAlign: 'center',
    };

    const radarData = [
		{
			"name": "帖子",
			"label": "点赞",
			"value": 10
		},
		{
			"name": "帖子",
			"label": "关注",
			"value": 8
		},
		{
			"name": "帖子",
			"label": "屏蔽",
			"value": 4
		},
		{
			"name": "帖子",
			"label": "热度",
			"value": 5
		},
		{
			"name": "帖子",
			"label": "贡献",
			"value": 7
		},
		{
			"name": "评论",
			"label": "点赞",
			"value": 3
		},
		{
			"name": "评论",
			"label": "关注",
			"value": 9
		},
		{
			"name": "评论",
			"label": "屏蔽",
			"value": 6
		},
		{
			"name": "评论",
			"label": "贡献",
			"value": 3
		},
		{
			"name": "评论",
			"label": "热度",
			"value": 1
		},
		{
			"name": "话题",
			"label": "点赞",
			"value": 4
		},
		{
			"name": "话题",
			"label": "关注",
			"value": 1
		},
		{
			"name": "话题",
			"label": "屏蔽",
			"value": 6
		},
		{
			"name": "话题",
			"label": "贡献",
			"value": 5
		},
		{
			"name": "话题",
			"label": "热度",
			"value": 7
		}
    ]
    
    const projectNotice = [
        {
            "id": "fresns",
            "logo": "/images/avatar.png",
            "member": "Fresns 官网",
            "href": "https://fresns.cn/"
        },
        {
            "id": "fresns-team",
            "logo": "/images/avatar.png",
            "member": "开源团队",
            "href": "https://fresns.cn/community/team.html"
        },
        {
            "id": "fresns-partners",
            "logo": "/images/avatar.png",
            "member": "合作伙伴",
            "href": "https://fresns.cn/community/partners.html"
        },
        {
            "id": "fresns-join",
            "logo": "/images/avatar.png",
            "member": "加入我们",
            "href": "https://fresns.cn/community/join.html"
        },
        {
            "id": "fresns-discuss",
            "logo": "/images/avatar.png",
            "member": "支持社区",
            "href": "https://discuss.fresns.cn/"
        },
        {
            "id": "fresns-apps",
            "logo": "/images/avatar.png",
            "member": "应用商店",
            "href": "https://apps.fresns.cn/"
        }
    ]

    const activities = [
        {
            "id": "trend-1",
            "updatedAt": "2021-04-18T15:40:35.234Z",
            "user": {
                "name": "曲丽丽",
                "avatar": "https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"
            },
            "group": {
                "name": "高逼格设计天团",
                "link": "#"
            },
            "project": {
                "name": "六月迭代",
                "link": "#"
            },
            "template": "在 @{group} 新建项目 @{project}"
        },
        {
            "id": "trend-2",
            "updatedAt": "2021-04-18T15:40:35.234Z",
            "user": {
                "name": "付小小",
                "avatar": "https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"
            },
            "group": {
                "name": "高逼格设计天团",
                "link": "#"
            },
            "project": {
                "name": "六月迭代",
                "link": "#"
            },
            "template": "在 @{group} 新建项目 @{project}"
        },
        {
            "id": "trend-3",
            "updatedAt": "2021-04-18T15:40:35.234Z",
            "user": {
                "name": "林东东",
                "avatar": "https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"
            },
            "group": {
                "name": "中二少女团",
                "link": "#"
            },
            "project": {
                "name": "六月迭代",
                "link": "#"
            },
            "template": "在 @{group} 新建项目 @{project}"
        },
        {
            "id": "trend-4",
            "updatedAt": "2021-04-18T15:40:35.234Z",
            "user": {
                "name": "周星星",
                "avatar": "https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"
            },
            "project": {
                "name": "5 月日常迭代",
                "link": "#"
            },
            "template": "将 @{project} 更新至已发布状态"
        },
        {
            "id": "trend-5",
            "updatedAt": "2021-04-18T15:40:35.234Z",
            "user": {
                "name": "朱偏右",
                "avatar": "https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"
            },
            "project": {
                "name": "工程效能",
                "link": "#"
            },
            "comment": {
                "name": "留言",
                "link": "#"
            },
            "template": "在 @{project} 发布了 @{comment}"
        },
        {
            "id": "trend-6",
            "updatedAt": "2021-04-18T15:40:35.234Z",
            "user": {
                "name": "乐哥",
                "avatar": "https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"
            },
            "group": {
                "name": "程序员日常",
                "link": "#"
            },
            "project": {
                "name": "品牌迭代",
                "link": "#"
            },
            "template": "在 @{group} 新建项目 @{project}"
        }
    ]

    const renderActivities = (item: any) => {
        const events = item.template.split(/@\{([^{}]*)\}/gi).map(key => {
          if (item[key]) {
            return (
              <a href={item[key].link} key={item[key].name}>
                {item[key].name}
              </a>
            );
          }
          return key;
        });
        return (
          <List.Item key={item.id}>
            <List.Item.Meta
              avatar={<Avatar src={item.user.avatar} />}
              title={
                <span>
                  <a className={styles.username}>{item.user.name}</a>
                  &nbsp;
                  <span className={styles.event}>{events}</span>
                </span>
              }
              description={
                <span className={styles.datetime} title={item.updatedAt}>
                  {moment(item.updatedAt).fromNow()}
                </span>
              }
            />
          </List.Item>
        );
      };

    const PageHeaderContent = () => {
        // const loading = currentUser && Object.keys(currentUser).length;
        // if (!loading) {
        //   return <Skeleton avatar paragraph={{ rows: 1 }} active />;
        // }
        return (
          <div className={styles.pageHeaderContent}>
            <div className={styles.avatar}>
              <Avatar size="large" src="/images/avatar.png" />
            </div>
            <div className={styles.content}>
              <div className={styles.contentTitle}>欢迎使用 Fresns</div>
              <div>当前您正在使用 Fresns 独立部署版控制面板 <a href="https://gitee.com/jyq/fresns-control-panel" target="_blank">v1.3</a></div>
            </div>
          </div>
        );
      };

    return (
        <PageHeaderWrapper
            content={<PageHeaderContent />}
        >
        <Row gutter={24}>
            <Card bodyStyle={{ paddingTop: 12, paddingBottom: 12 }} bordered={false} title="Fresns 官方信息">
              <div className={styles.members}>
                <Row gutter={48}>
                  {projectNotice.map(item => (
                    <Col span={12} key={`members-item-${item.id}`}>
                      <a onClick={()=>{window.open(item.href,'_blank')}} target="_blank">
                        <div>
                          <Avatar src={item.logo} size="small" />
                          <span className={styles.member}>{item.member}</span>
                        </div>
                      </a>
                    </Col>
                  ))}
                </Row>
              </div>
            </Card>
        </Row>
        </PageHeaderWrapper>
    );
};

/**
* 添加节点
* @param fields
*/
const handleAdd = async (fields: any) => {
    return RequestHelper.bdExec({
        fn: addRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.store-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
    });
};

/**
* 更新节点
* @param fields
*/
const handleUpdate = async (fields: FormValueType) => {
    return RequestHelper.bdExec({
        fn: updateRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.update-success' }),
        failMsg:  formatMessage({ id: 'app.base.api-exception' }),
    });
};

// @ts-ignore
/**
 *  删除节点
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
    if (!selectedRows) return true;
    const ids:any = selectedRows.map(row => row.id).toString();
    return RequestHelper.bdExec({
        fn: removeRule,
        args: {ids},
        successMsg: formatMessage({ id: 'app.base.destroy-success' }),
        failMsg:  formatMessage({ id: 'app.base.api-exception' }),
        hasLoading: false
    });
};


export default Form.create<TableListProps>()(TableList);
